有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从字符串Java中提取葡萄牙语日期

我想从字符串中提取数据,这个字符串有时会以不同的方式出现。例如,它可以是以下任何一种:

Portaria n° 200, 28 de janeiro de 2018.

Portaria n° 200, 28 de janeiro de 2018 da Republica Brasileira.

Portaria n° 200 28 de janeiro de 2018.

Portaria n° 200 2017/2018 de 28 de janeiro de 2018.

没有模式。我尝试过xsplit:它在某些情况下有效,但并不总是有效

    String receberTextoIdentifica = (xmlUtil.xpathElement(documentOrigem, Constantes.GETIDENTIFICACAO).getTextContent());
    LocalDateTime receberDataEnvio = materiaDto.getDataEnvio();
    Integer receberDataEnvioAno = receberDataEnvio.getYear();
    if (receberTextoIdentifica != null && receberTextoIdentifica.toLowerCase().contains("" + receberDataEnvioAno)) {
        Element dataTexto = documentDestino.createElement("dataTexto");
        estruturas.appendChild(dataTexto);
        receberTextoIdentifica = receberTextoIdentifica.substring(0, receberTextoIdentifica.indexOf("" + receberDataEnvioAno) + 4);
        String words[] = receberTextoIdentifica.split(" ");
        String lastFive = words[words.length - 5] + " " + words[words.length - 4] + " " + words[words.length - 3] + " "
                + words[words.length - 2] + " " + words[words.length - 1];
        dataTexto.setTextContent(lastFive);

共 (1) 个答案

  1. # 1 楼答案

    首先使用正则表达式在字符串中查找日期,然后使用DateTimeFormatter将其解析为LocalDate

        Pattern datePattern = Pattern.compile("\\d{1,2} de [a-zç]{4,9} de \\d{4}");
        DateTimeFormatter portugueseDateFormatter
                = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
                        .withLocale(Locale.forLanguageTag("pt-BR"));
    
        String[] differentStrings = {
                "Portaria n° 200, 28 de janeiro de 2018.",
                "Portaria n° 200, 28 de janeiro de 2018 da Republica Brasileira.",
                "Portaria n° 200 28 de janeiro de 2018.",
                "Portaria n° 200 2017/2018 de 28 de janeiro de 2018."
        };
    
        for (String s : differentStrings) {
            Matcher m = datePattern.matcher(s);
            if (m.find()) {
                String dateString = m.group();
                LocalDate date = LocalDate.parse(dateString, portugueseDateFormatter);
                System.out.println("Date found: " + date);
            } else {
                System.out.println("No date found in " + s);
            }
        }
    

    输出为:

    Date found: 2018-01-28
    Date found: 2018-01-28
    Date found: 2018-01-28
    Date found: 2018-01-28
    

    正则表达式接受一个或两个数字表示月份的日期,然后是de(前后有空格),四到九个小写字母表示月份名称,包括ç,如março(三月),de和四位年份

    您可能希望从解析中捕获DateTimeParseException,甚至可能再次尝试find,以查看字符串中的实际日期是否在后面